package action;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.heantai.easystruts.controller.Action;
import com.heantai.easystruts.form.ActionForm;

import dao.DaoFactory;
import dao.PhotoDao;
import entity.Photo;

public class UploadPhotoAction extends Action {

	@Override
	public String execute(ActionForm actionForm,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("id"));
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		List<FileItem> fileItems = sfu.parseRequest(request);
		for (int i = 0; i < fileItems.size(); i++) {
			FileItem item = fileItems.get(i);
			if (!item.isFormField()) {
				String type = item.getContentType();
				if (type.toLowerCase().endsWith("jpeg")) {
					String fileName = item.getName();
					fileName = fileName
							.substring(fileName.lastIndexOf("/") + 1);
					Photo photo = new Photo();
					photo.setUserId(id);
					photo.setName(fileName);
					PhotoDao dao = DaoFactory.getInstance(PhotoDao.class);
					dao.save(photo);

					String userPhotosFolder = request.getSession()
							.getServletContext().getRealPath(
									"/photos/photo_" + id);
					File file = new File(userPhotosFolder + "/" + fileName);
					item.write(file);
				}
			}
		}
		response.sendRedirect("userDetail.jsp?id=" + id);
		return "userDetail";
	}

}
